package com.sky.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.dataTransmit.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.view.UserLoginVO;
import com.sky.view.UserReportVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private WeChatProperties weChatProperties;

    //微信接口服务地址
    private static final String WX_LOGIN="https://api.weixin.qq.com/sns/jscode2session";

    //用户登录
    @Override
    public UserLoginVO login(UserLoginDTO userLoginDTO) {
        String openid = getOpenid(userLoginDTO.getCode());
        //如果openid为空则抛出异常
        if(openid==null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }else {
            //根据openid查询用户
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<User>()
                    .eq(User::getOpenid, openid);
            User user = getOne(queryWrapper);
            //如果user为空则注册为用户
            if(user==null){
                user = User.builder()
                        .openid(openid)
                        .createTime(LocalDateTime.now()).build();
                save(user);
            }
            HashMap<String, Object> claims = new HashMap<>();
            claims.put(JwtClaimsConstant.USER_ID,user.getId());
            String authentication = JwtUtil.createJWT(jwtProperties.getUserSignKey(), jwtProperties.getUserTtl(), claims);
            UserLoginVO userLoginVO = BeanUtil.copyProperties(user, UserLoginVO.class);
            userLoginVO.setToken(authentication);
            return userLoginVO;
        }
    }

    //统计总用户数量和新增用户数量
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        //生成日新增用户字符串
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<User>()
                .between(User::getCreateTime, beginTime, endTime);
        List<User> list = list(queryWrapper);
        Map<LocalDate, Long> collect = list.stream()
                .collect(Collectors.groupingBy(u -> u.getCreateTime().toLocalDate(), Collectors.counting()));
        for (LocalDate date = begin; date.isBefore(end.plusDays(1)); date = date.plusDays(1)) {
            collect.putIfAbsent(date, 0L);
        }
        ArrayList<Long> userList = new ArrayList<>(collect.values());
        String newUserListString = StringUtils.join(userList, ",");
        //生成日用户总数字符串
        LambdaQueryWrapper<User> queryWrapper1 = new LambdaQueryWrapper<User>()
                .lt(User::getCreateTime, beginTime);
        long count = count(queryWrapper1);
        userList.set(0,count+userList.get(0));
        for (int i = 1; i < userList.size(); i++) {
            userList.set(i,userList.get(i)+userList.get(i-1));
        }
        String totalUserListString = StringUtils.join(userList, ",");
        //生成日期字符串
        ArrayList<LocalDate> dateList = new ArrayList<>();
        while (!begin.equals(end)){
            dateList.add(begin);
            begin=begin.plusDays(1);
        }
        dateList.add(end);
        String dateListString = StringUtils.join(dateList, ",");
        return new UserReportVO(dateListString,totalUserListString,newUserListString);
    }

    //调用微信接口id，获取openid
    private String getOpenid(String code) {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("appid",weChatProperties.getAppid());
        hashMap.put("secret",weChatProperties.getSecret());
        hashMap.put("js_code", code);
        hashMap.put("grant_type","authorization_code");
        String data = HttpClientUtil.doGet(WX_LOGIN, hashMap);
        JSONObject jsonObject = JSON.parseObject(data);
        String openid = jsonObject.getString("openid");
        return openid;
    }
}
